<?php

use Yaf\Registry;
use Yaf\Exception;
use models\Service\RefundinfoService;
use models\Service\OrderService;
use Task\client;
use models\Business\Tbk\TkUrl;
use models\Business\Tbk\TbkOrder;
use models\Business\Tbk\TbkSdk\Tbk;
use models\DAO\OrderModel;
use models\Service\AlibabaproductService;
use models\Business\Order;
use models\Exception\Business\OrderException;
use models\Exception\Business\TbkorderException;
use models\Business\Booking;

class CrontabController extends ApiBaseController
{
    /**
     * 命令行启动 每1小时执行一次
     * 获取数据库中"已付款"的tbk订单，去调用接口获取判断是否"已结算"
     */
    public function chkSettleTbkOrderAction() {
        $order = TbkOrder::getOrderList([
            'order_stats' => 2
        ]);
        Registry::get('crontab_log')->info('每小时从数据库中读取"已付款"的订单，并去接口查询是否结算');
        if (! $order || $order['meta']['total'] <= 0)
            throw new TbkorderException(TbkorderException::TBKORDER_IS_NOT_EXISTS, TbkorderException::TBKORDER_IS_NOT_EXISTS_NO);

        $client = new client();
        foreach ($order['data'] as $order_info) {
            Registry::get('crontab_log')->info("异步任务查询" . $order_info['order_sn'] . '的订单状态');
            try {
                $client->connect();
                $client->chkTbkOrderIsSettled($order_info['order_sn'],
                    $order_info['pay_time'], date('Y-m-d H:i:s', strtotime($order_info['pay_time']) + 60));
            } catch (\Exception $e) {
                Registry::get('crontab_log')->err("调用chkTbkOrderIsSettled失败" . $e->getMessage());
            } finally {
                $client->close();
            }
        }
        $client->close();

        return $this->_responseString('success');
    }

    /**
     * 异步任务查询淘宝客订单状态
     * 批量修改商品浏览量
     */
    public function getSettledTbkOrderAction() {
//        $parameters = $this->getRequest()->getParams();
        $parameters = Registry::get('parameters');
        Registry::get('crontab_log')->info('查询接口的参数:' . json_encode($parameters));
        $param = [
            'start_time' => $parameters['start_time'],
            'end_time' => $parameters['end_time'],
            'page_no' => 1,
            'page_size' => 1,
            'query_type' => 1,
            'tk_status' => 3
        ];

        Registry::get('crontab_log')->info('查询接口的参数:' . json_encode($param));
        list($position_index, $order_arr, $has_next) = \models\Business\Tbk\TkUrl::getOrderList($param);

        if (empty($order_arr))
            Registry::get('crontab_log')->info('淘宝订单编号为：' . $parameters['sn'] . '订单查询不到结算信息');

        foreach ($order_arr as $idx => $order_info) {
            if ($order_info['order_sn'] == $parameters['sn']) {
                // 已结算
                if ($order_info['order_stats'] !== 4) {
                    unset($order_arr[$idx]);
                    Registry::get('crontab_log')->info('淘宝客订单编号为：' . $parameters['sn'] . '的订单状态为' . $order_info['order_stats']);
                }
            }
        }

        if (!empty($order_arr)) {
            try {
                TbkOrder::collectTbkOrder($order_arr);
            } catch (\Exception $e) {
                Registry::get('tbk_log')->err("订单编号为：" . $parameters['sn'] . "的订单数据更新失败 - " . $e->getMessage());
            }

            try {
                $member_id = Tbk::getTbkOrderMemberIdBySn($parameters['sn']);
                if (!empty($member_id))
                    TbkOrder::rebate($parameters['sn'], $member_id);
            } catch (\Exception $e) {
                Registry::get('tbk_log')->err("订单编号为：" . $parameters['sn'] . "给下单会员及其上级、上上级新增淘宝返利余额时报错 - " . $e->getMessage());
            }
        }

        return $this->_responseString('success');
    }

    /**
     * 命令行启动 每10分钟执行一次
     * 将过期的自动拼单数据重新发起自动拼单
     */
    public function resetAutoCouponAction() {
        $booking = Booking::getBookingList(['stats' => 20,
            'end_expired_at' => date('Y-m-d H:i:s', time()), 'page' => 1, 'page_size' => 999, 'sort' => 'desc', 'order' => 'created_at']);

        if (isset($booking['data']) && !empty($booking['data'])) {
            Registry::get('crontab_log')->info('过期的自动拼单商品: ' . json_encode(array_column($booking['data'], 'product_id')));
            $system = \models\Business\System::getSystemInfo(1);
            foreach ($booking['data'] as $booking_info) {
                $rand_time = mt_rand(10, 50);
                Booking::handlerMachineBookingByProductId($booking_info['product_id'],
                    date('Y-m-d H:i:s', strtotime($booking_info['created_at']) + $rand_time),
                    date('Y-m-d H:i:s', strtotime($booking_info['expired_at']) + $rand_time + $system['coupon_expire']));
            }
            $this->_responseString('success');
        } else {
            Registry::get('crontab_log')->info("没有过期的自动拼单");
            $this->_responseString('success');
        }
    }
}
